package AionCrafter.ui;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import AionCrafter.AionCrafterApplication;
import AionCrafter.data.Material;
import AionCrafter.data.Recipe;

public class SubComponentsPanel extends JPanel implements DocumentListener {
	private Recipe currentRecipe;
	
	//UI Parts
	JFormattedTextField quantity = new JFormattedTextField();
	JTextArea scDisplay = new JTextArea();
	JTextArea vendorDisplay = new JTextArea();
	JTextArea gatherDisplay = new JTextArea();
	JTextField vendorSumField = new JTextField();
	
	Map<String,Recipe> recipeMap;
	Map<Material,Integer> vendorList = new HashMap<Material,Integer>();
	Map<Material,Integer> gatheredList = new HashMap<Material,Integer>();
	
	private int taxRate = 10;
	private int serverPrices = 100;
	
	public void init(){
		this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
		
		//Quantity
		JPanel quantityPanel = new JPanel();
		quantityPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		quantity.setText("1");
		quantity.setPreferredSize(new Dimension(40,20));
		quantity.getDocument().addDocumentListener(this);
		quantityPanel.add(quantity);
		quantityPanel.add(new JLabel("Number of Crafts"));
		
		//SubComponent Display
		JPanel scPanel = new JPanel();
		scPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		scPanel.setPreferredSize(new Dimension(400,150));
		scDisplay.setEditable(false);
		scDisplay.setWrapStyleWord(true);
		JScrollPane scScroll = new JScrollPane(scDisplay);
		TitledBorder scTitle = BorderFactory.createTitledBorder("Sub-Components");
		scScroll.setBorder(scTitle);
		scScroll.setPreferredSize(new Dimension(400,150));
		scScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
		scScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scPanel.add(scScroll);
		
		//Lower lists
		JPanel scLists = new JPanel();
		scLists.setLayout(new FlowLayout(FlowLayout.LEFT));
		
		vendorDisplay.setEditable(false);
		JScrollPane vendorScroll = new JScrollPane(vendorDisplay);
		TitledBorder vendorTitle = BorderFactory.createTitledBorder("Vendor Materials");
		vendorScroll.setBorder(vendorTitle);
		vendorScroll.setPreferredSize(new Dimension(200,160));
		vendorScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
		vendorScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scLists.add(vendorScroll);
		
		gatherDisplay.setEditable(false);
		JScrollPane gatherScroll = new JScrollPane(gatherDisplay);
		TitledBorder gatherTitle = BorderFactory.createTitledBorder("Gathered Materials");
		gatherScroll.setBorder(gatherTitle);
		gatherScroll.setPreferredSize(new Dimension(200,160));
		gatherScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
		gatherScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scLists.add(gatherScroll);
		
		JPanel vendorSumPanel = new JPanel();
		vendorSumPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		JLabel vendorSumLabel = new JLabel("Vendor mats price");
		vendorSumField.setPreferredSize(new Dimension(100,20));
		vendorSumField.setEditable(false);
		vendorSumPanel.add(vendorSumField);
		vendorSumPanel.add(vendorSumLabel);
		
		//Bottom Buttons
		JPanel bottomButtons = new JPanel();
		bottomButtons.setLayout(new FlowLayout(FlowLayout.RIGHT));
		JButton clipboardButton = new JButton("Copy materials to clipboard");
		JButton orderButton = new JButton("Add to current order");
		bottomButtons.add(clipboardButton);
		bottomButtons.add(orderButton);
		
		//Finalize Panel
		this.add(quantityPanel);
		this.add(scPanel);
		this.add(scLists);
		this.add(vendorSumPanel);
		this.add(bottomButtons);
	}
	
	public void changeRecipe(Recipe recipe, int quantity, Map<String,Recipe> recipeMap){
		if(recipeMap != null){
			this.recipeMap = recipeMap;
		}
		if(recipe != null){
			setRecipe(recipe);
		}
		Map<String,Integer> quantityMap = new HashMap<String,Integer>();
		scDisplay.setText(recipe.getSubcomponentDisplay(quantity, recipeMap, 0, quantityMap));
		vendorList.clear();
		gatheredList.clear();
		
		Iterator itr = quantityMap.entrySet().iterator();
		while(itr.hasNext()){
			Map.Entry<String,Integer> pair = (Map.Entry<String,Integer>) itr.next();			
			//All vendor mats have "shopmaterial" in their id
			if(((String)pair.getKey()).contains("shopmaterial")){
				vendorList.put(AionCrafterApplication.materialList.getMaterials().get(pair.getKey()), pair.getValue());
			} else if(!((String)pair.getKey()).contains("_part_")){
				//check to see if the gathered mat is already there from another component
				if(!gatheredList.containsKey(AionCrafterApplication.materialList.getMaterials().get(pair.getKey()))){
					gatheredList.put(AionCrafterApplication.materialList.getMaterials().get(pair.getKey()), pair.getValue());
				} else {
					//if already there, add to the existing total
					gatheredList.put(AionCrafterApplication.materialList.getMaterials().get(pair.getKey()), 
							gatheredList.get(AionCrafterApplication.materialList.getMaterials().get(pair.getKey())) 
							+ pair.getValue());
					
				}
			}
		}
		setVendorList();
		setGatheredList();
	}
	
	public void setRecipe(Recipe r){
		currentRecipe = r;
	}
	
	public void setTaxRate(int r){
		taxRate = r;
		setVendorList();
	}
	
	public void setServerPrices(int p){
		serverPrices = p;
		setVendorList();
	}
	
	private void setVendorList(){
		//Prices at npc are (price * (1+(tax rate + "prices")*2))
		String prices = "";
		int totalPrice = 0;
		Iterator itr = vendorList.entrySet().iterator();
		while(itr.hasNext()){
			Map.Entry<Material, Integer> pair = (Map.Entry<Material,Integer>) itr.next();
			double price = (pair.getKey().getPrice() * (1+(taxRate/100.0 + (serverPrices-100)/100.0)*2));
			prices += pair.getKey().getName() + "(" + pair.getValue() + "): " + (int)price + " ea.\n";
			totalPrice += (int)price * pair.getValue();
		}
		vendorDisplay.setText(prices);
		
		vendorSumField.setText(Integer.toString(totalPrice));
	}
	
	private void setGatheredList(){
		String text = "";
		Iterator itr = gatheredList.entrySet().iterator();
		while(itr.hasNext()){
			Map.Entry<Material, Integer> pair = (Map.Entry<Material,Integer>) itr.next();
			text += pair.getKey().getName() + "(" + pair.getValue() + ")\n";
		}
		gatherDisplay.setText(text);
	}

	@Override
	public void changedUpdate(DocumentEvent e) {
		if(e.getDocument() == quantity.getDocument() && recipeMap != null && currentRecipe != null){
			try{
				changeRecipe(currentRecipe, Integer.parseInt(quantity.getText()), recipeMap);
			} catch (NumberFormatException ex){
				return;
			}
		}
	}

	@Override
	public void insertUpdate(DocumentEvent e) {
		if(e.getDocument() == quantity.getDocument() && recipeMap != null && currentRecipe != null){
			try{
				changeRecipe(currentRecipe, Integer.parseInt(quantity.getText()), recipeMap);
			} catch (NumberFormatException ex){
				return;
			}
		}
	}

	@Override
	public void removeUpdate(DocumentEvent e) {
		if(e.getDocument() == quantity.getDocument() && recipeMap != null && currentRecipe != null){
			try{
				changeRecipe(currentRecipe, Integer.parseInt(quantity.getText()), recipeMap);
			} catch (NumberFormatException ex){
				return;
			}
		}
	}

}
